package me.thinkjet.sso.server.ticket.Registry;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import me.thinkjet.sso.server.ticket.ServiceTicket;
import me.thinkjet.sso.server.ticket.Ticket;
import me.thinkjet.sso.server.ticket.TicketGrantingTicket;

/**
 * 
 * @ClassName ServiceTicketRegistry
 * @author johnny_zyc
 * @Modified 2013-3-2 下午2:48:33
 * 
 */
public final class ServiceTicketRegistry {

	private final Map<String, ServiceTicket> cache;

	public ServiceTicketRegistry() {
		this.cache = new ConcurrentHashMap<String, ServiceTicket>();
	}

	public ServiceTicketRegistry(int initialCapacity, final float loadFactor,
			final int concurrencyLevel) {
		this.cache = new ConcurrentHashMap<String, ServiceTicket>(
				initialCapacity, loadFactor, concurrencyLevel);
	}

	/**
	 * @throws IllegalArgumentException
	 *             if the Ticket is null.
	 */
	public void addTicket(final ServiceTicket ticket) {
		this.cache.put(ticket.getId(), ticket);
	}

	public ServiceTicket getTicket(final String ticketId) {
		if (ticketId == null) {
			return null;
		}

		ServiceTicket ticket = this.cache.get(ticketId);

		if (ticket != null) {
		}

		return ticket;
	}

	public boolean deleteTicket(final String ticketId) {
		if (ticketId == null) {
			return false;
		}
		return (this.cache.remove(ticketId) != null);
	}

	public Collection<ServiceTicket> getTickets() {
		return Collections.unmodifiableCollection(this.cache.values());
	}

	public int sessionCount() {
		int count = 0;
		for (Ticket t : this.cache.values()) {
			if (t instanceof TicketGrantingTicket) {
				count++;
			}
		}
		return count;
	}

	public int serviceTicketCount() {
		int count = 0;
		for (Ticket t : this.cache.values()) {
			if (t instanceof ServiceTicket) {
				count++;
			}
		}
		return count;
	}

}
